import Router from '@koa/router';
import db from '../mysqlHelper.js';
import logger from '../logger.js';
import response from '../response.js';
import moment from 'moment';
import md5 from 'md5';


const router = new Router();
router.prefix('/api');


router.post('/:table/insert', async (ctx) => {
    let body = ctx.request.body;
    if(ctx.state.oper?.name == null) {
        ctx.body = response.fail('非法的操作员禁止调用该接口');
        return;
    }
    if (ctx.state.oper == null) {
        if (ctx.state.openid == null) {
            ctx.body = response.fail('请先登录');
            return;
        }
        else {
            ctx.body = response.fail('该token无插入数据的权限');
            return;
        }
    }
    if (ctx.params.table == 'oper') {
        ctx.body = response.fail('无权访问');
        return;
    }
    if (body == null) {
        ctx.body = response.fail('参数不允许为空');
        return;
    }
    let isExist = false;
    switch (ctx.params.table) {
        case 'merchant':
            if (body.name == null) {
                ctx.body = response.fail('缺少必填字段 商户名称');
                return;
            }
            isExist = await db.checkExist('merchant', { name: body.name });
            if (isExist) {
                ctx.body = response.fail('相同名称的商户已存在');
                return;
            }
            break;
        case 'community':
            if (body.name == null) {
                ctx.body = response.fail('缺少必填字段 名称');
                return;
            }

            isExist = await db.checkExist('community', { name: body.name });
            if (isExist) {
                ctx.body = response.fail('相同名称已存在');
                return;
            }
            break;
        case 'meter':
            if(body.mac == null) {
                ctx.body = response.fail('缺少必填字段 电表mac');
                return;
            }
            isExist = await db.checkExist('meter', { mac: body.mac });
            if (isExist) {
                ctx.body = response.fail('相同mac的电表已存在');
                return;
            }
            break;
        default:
            break;
    }
    console.log(`操作员:${ctx.state.oper.name} 调用插入接口 表名:${ctx.params.table} body:${JSON.stringify(body)}`);
    let res = await db.create(ctx.params.table, body);
    if (res instanceof Error) {
        logger.error(`${ctx.params.table} create error :` + res.message);
        ctx.body = response.fail(`${ctx.params.table} create error :` + res.message);
        return;
    }
    ctx.body = response.success();

});
function getConditions(tbaleName, body) {
    let conditions = {};
    //根据不同的表获取表的主键用于后续的更新和删除
    switch (tbaleName) {

        case 'meter':
            if (body.mac == null) {
                return { code: 0, conditions, msg: '缺少必填字段 mac' };
            }
            conditions = { mac: body.mac };
            return { code: 1, conditions: conditions };
        default:
            if (body.id == null) {
                return { code: 0, conditions, msg: '缺少必填字段 id' };
            }
            conditions = { id: body.id };
            return { code: 1, conditions: conditions };
    }
}

router.post('/:table/update', async (ctx) => {
    if(ctx.state.oper?.name == null) {
        ctx.body = response.fail('非法的操作员禁止调用该接口');
        return;
    }
    let body = ctx.request.body;
    if (ctx.params.table == 'oper') {
        ctx.body = response.fail('无权访问');
        return;
    }
    if (body == null) {
        ctx.body = response.fail('参数不允许为空');
        return;
    }
    let res = getConditions(ctx.params.table, body);
    if (res.code == 0) {
        ctx.body = response.fail(res.msg);
        return;
    }
    let conditions = res.conditions;
    let obj = await db.findOne(ctx.params.table, conditions);
    if (obj == null) {
        ctx.body = response.fail('要修改数据不存在');
        return;
    }
    delete body.conditions;
    console.log(`操作员:${ctx.state.oper.name} 调用更新接口 表名:${ctx.params.table} conditions:${JSON.stringify(conditions)} , body:${JSON.stringify(body)}`);
    res = await db.update(ctx.params.table, body, conditions);
    if (res instanceof Error) {
        logger.error(`${ctx.params.table} update error :` + res.message);
        ctx.body = response.fail(`${ctx.params.table} update error :` + res.message);
        return;
    }
    ctx.body = response.success();
});

router.post('/:table/remove', async (ctx) => {
    if(ctx.state.oper?.name == null) {
        ctx.body = response.fail('非法的操作员禁止调用该接口');
        return;
    }
    let body = ctx.request.body;
    if (ctx.params.table == 'oper') {
        ctx.body = response.fail('无权访问');
        return;
    }
    if (body == null) {
        ctx.body = response.fail('参数不允许为空');
        return;
    }
    let res = getConditions(ctx.params.table, body);
    if (res.code == 0) {
        ctx.body = response.fail(res.msg);
        return;
    }
    let conditions = res.conditions;
    console.log(`操作员:${ctx.state.oper.name} 调用删除接口 表名:${ctx.params.table} conditions:${JSON.stringify(conditions)}`);
    res = await db.deleteRow(ctx.params.table, conditions);
    if (res instanceof Error) {
        logger.error(`${ctx.params.table} delete error :` + res.message);
        ctx.body = response.fail(`${ctx.params.table} delete error :` + res.message);
        return;
    }
   
    ctx.body = response.success();
});
router.post('/:table/getList', async (ctx) => {
    let body = ctx.request.body;
    if (body == null) {
        body = { limit: 10, offset: 0, direction: 'desc' };
    } else {
        if (!body.direction) body.direction = 'desc';
    }
    if (ctx.params.table == 'oper') {
        ctx.body = response.fail('无权访问');
        return;
    }
    let res = await db.findAll(ctx.params.table, body.conditions, body.orderBy, body.direction, body.limit, body.offset, body.areaArr, body.likeArr, body.leftJoinArr, body.inArr, body.dispColumn, body.customizeWhere);
    if (res instanceof Error) {
        logger.error(`${ctx.params.table} getList error :` + res.message);
        ctx.body = response.fail(`${ctx.params.table} getList error :` + res.message);
        return;
    }
    if (res.count) {
        ctx.body = response.success({ rows: res.rows, count: res.count });
        return;
    } else {
        ctx.body = response.success(res);
    }
});






export { router };
